package com.ruoyi.yzz.token;

import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.secure.SaBase64Util;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.ITokenExtractor;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @author LIUJUN
 */
@Slf4j
public class HeaderInfoExtractor implements ITokenExtractor {

    public static final String PACKAGE_ALL = "packageAll";

    public static final String PARA_ASSEMBLE_MODE = "paraAssembleMode";

    public static final String LOGIN_USER_ID_KEY = "userId";

    public static final String LOGIN_ORG_ID_KEY = "orgId";

    public static final String USER_INFO_HEADER_KEY = "userInfo";

    @Override
    public LoginUser extract(SaRequest saRequest) {
        LoginUser loginUser = null;
        if (PACKAGE_ALL.equalsIgnoreCase(saRequest.getHeader(PARA_ASSEMBLE_MODE))) {
            String base64Text = saRequest.getHeader(USER_INFO_HEADER_KEY);
            if (StringUtils.isEmptyOrNull(base64Text)) {
                return null;
            }
            log.info("Using package mode,base64 code:{}", base64Text);
            try {
                String json = SaBase64Util.decode(base64Text);
                loginUser = JsonUtils.parseObject(json, LoginUser.class);
                assert loginUser != null;
                if (!loginUser.validate()) {
                    throw new RuntimeException();
                }
            } catch (Exception e) {
                log.warn("解析Header传入 LoginUser 信息异常，登录失败", e);
                return null;
            }
        } else {
            loginUser = new LoginUser();
            String userId = saRequest.getHeader("userId", "0");
            String orgId = saRequest.getHeader("orgId", "0");
            loginUser.setUsername(userId);
            loginUser.setDeptName("org_" + orgId);
            loginUser.setDeptNo(orgId);
            loginUser.setUserId(1L);
            loginUser.setDeptId(1L);
            log.info("Using single para mode,userId :{} ,orgId :{}", userId, orgId);
        }
        try {
            if (!loginUser.validate()) {
                log.warn("user info from header is not valid,info:{}", loginUser.toString());
                return null;
            }
            loginUser.setUserType(UserConstants.SYS_USER.toLowerCase());
        } catch (Exception e) {
            log.warn("Login by header exception");
            return null;
        }
        return loginUser;

    }
}
